//
//  HFUserAccountViewModel.swift
//  sinaMicroBlog
//
//  Created by mac on 15/11/12.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class HFUserAccountViewModel: NSObject {
    var account: HFUserAccount?
    
    var userLogin: Bool {
        return account?.access_token != nil
    }
    var token: String? {
        return account?.access_token
    }
    
    override init() {
        account = HFUserAccount.loadAccount()
    }
    //用户名和用户头像
    var userName:String? {
        return account?.name
    }
    var headImageUrl:NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    func loadAccessToken(code: String, finished: (error: NSError?) ->()) {
        
        let urlString = "oauth2/access_token"
        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        HFNetWorkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            if error != nil {
                print("-----------------------")
                print(error)
                finished(error: error)
                return
            }

            let account = HFUserAccount(dic:result!)
                //获取用户信息
            self.loadUserInfo(account, finished: finished)
            }
        }
    private func loadUserInfo(account: HFUserAccount, finished: ((error: NSError?)->())) {
        
        let urlString = "2/users/show.json"
        let parameters = ["access_token" : account.access_token!, "uid" : account.uid!]
        
        HFNetWorkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters:parameters) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            
            //请求用户信息
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            account.saveAccount()
            finished(error: nil)
            }
        }
}
